package com.tmall.testgen.plugin;

import java.io.PrintWriter;
import java.io.StringWriter;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.IConsoleManager;
import org.eclipse.ui.console.MessageConsole;
import org.eclipse.ui.console.MessageConsoleStream;

/**
 * 
 * @author liuzx
 * 
 */
public class ConsoleFactory {
	public static MessageConsole console = new MessageConsole(
			"tmall testgen console", null);
	private static MessageConsoleStream consoleOut = null;
	private static Color red;
	private static Color old;

	private static void showConsole() {
		if (console != null) {
			red = Display.getCurrent().getSystemColor(SWT.COLOR_RED);//
			IConsoleManager manager = ConsolePlugin.getDefault()
					.getConsoleManager();
			IConsole[] existing = manager.getConsoles();
			boolean exists = false;
			for (int i = 0; i < existing.length; i++) {
				if (console == existing[i]) {
					exists = true;
				}
			}
			if (!exists) {
				manager.addConsoles(new IConsole[] { console });
			}
			manager.showConsoleView(console);
			consoleOut = console.newMessageStream();
			old = consoleOut.getColor();
		}
	}

	public static void putLog(final String msg){
		putMessage(msg);
	}
	public static void putMessage(final String msg) {
		try {
			Display.getDefault().syncExec(new Runnable() {
				@Override
				public void run() {
					showConsole();
					consoleOut.setColor(old);
					if (consoleOut != null) {
						consoleOut.println(msg);
					} else {
						System.out.println(msg);
					}
				}
			});
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static void putError(final Throwable e) {
		try {
			Display.getDefault().syncExec(new Runnable() {
				@Override
				public void run() {
					showConsole();
					consoleOut.setColor(red);
					StringWriter sw = new StringWriter();  
		            PrintWriter pw = new PrintWriter(sw);  
		            e.printStackTrace(pw);  
		            consoleOut.print(sw.toString());
				}
			});
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}

	public static void closeConsole() {
		IConsoleManager manager = ConsolePlugin.getDefault()
				.getConsoleManager();
		if (console != null) {
			manager.removeConsoles(new IConsole[] { console });
		}
	}

	public static void main(String[] args) throws Exception {
		
		showConsole();
		try {
			Thread.sleep(60000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		closeConsole();
	}
}
